import { execa } from 'execa'
import { g_pkg, targets } from './utils.js'
import fs from 'node:fs/promises'
import { existsSync } from 'node:fs'

const sourceMap = true

async function runParallel(source, iteratorFn) {
  const result = []
  for (const f of source) {
    const p = Promise.resolve().then(() => iteratorFn(f))
    result.push(p)
  }
  return Promise.all(result)
}

async function build(target) {
  const dfs = `${g_pkg.targetsDir}/${target}/dist`
  if (existsSync(dfs)) {
    await fs.rm(dfs, { recursive: true })
  }
  
  await execa('rollup', [
    '-c',
    '--environment',
    [
      `TARGET:${target}`,
      sourceMap ? `SOURCE_MAP:true` : ``
    ].filter(Boolean).join(',')], 
    //  让子进程的输出在父进程中查看
    { stdio: 'inherit' }
  )
}

runParallel(targets, build).then(() => {
  console.log('完成')
})